"""
更新角色数据，添加缺失的 scope 字段
"""
import asyncio
import sys
from pathlib import Path

# 添加项目根目录到 Python 路径
project_root = Path(__file__).parent.parent
sys.path.insert(0, str(project_root))

from motor.motor_asyncio import AsyncIOMotorClient
from app.core.config import settings
from app.models.role import RoleScope
import logging

logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)


async def update_roles_scope():
    """更新所有角色，添加 scope 字段"""
    # 连接数据库
    client = AsyncIOMotorClient(settings.MONGODB_URL)
    db = client[settings.MONGODB_DATABASE]
    
    try:
        # 查找所有没有 scope 字段的角色
        roles_without_scope = await db.roles.find({"scope": {"$exists": False}}).to_list(length=None)
        
        logger.info(f"找到 {len(roles_without_scope)} 个缺少 scope 字段的角色")
        
        updated_count = 0
        for role in roles_without_scope:
            role_code = role.get("code", "")
            role_name = role.get("name", "")
            
            # 根据角色代码判断作用域
            # 系统级角色：admin, user
            # 项目级角色：其他所有角色
            if role_code in ["admin", "user"]:
                scope = RoleScope.SYSTEM
            else:
                scope = RoleScope.PROJECT
            
            # 更新角色
            result = await db.roles.update_one(
                {"_id": role["_id"]},
                {"$set": {"scope": scope}}
            )
            
            if result.modified_count > 0:
                updated_count += 1
                logger.info(f"更新角色: {role_name} ({role_code}) -> scope: {scope}")
        
        logger.info(f"成功更新 {updated_count} 个角色的 scope 字段")
        
    except Exception as e:
        logger.error(f"更新角色失败: {str(e)}")
        raise
    finally:
        client.close()


if __name__ == "__main__":
    asyncio.run(update_roles_scope())
